package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.customer.CustomerDO;
import com.qk.dto.customer.CustomerDTO;
import com.qk.dto.customer.CustomerListDTO;
import com.qk.dto.customer.UpdateCustomerDTO;
import com.qk.entity.Customer;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 客户管理服务实现类
 * @Author:Mr.m
 * @Date: 2025-10-17 20:30
 * @Description:
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    private CustomerMapper customerMapper;


    /**
     * 修改客户
     *
     * @param dto
     */
    @Override
    public void updateCustomer(UpdateCustomerDTO dto) {
        //校验参数
        if(ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getName())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //设置更新时间
        dto.setUpdateTime(LocalDateTime.now());
        customerMapper.updateCustomer(dto);
    }

    /**
     * 查询客户id
     *
     * @param id
     * @return
     */
    @Override
    public Customer queryCustomerById(Integer id) {
        Customer customer = baseMapper.selectById(id);
        return customer;
    }

    /**
     * 添加客户
     *
     * @param dto
     */
    @Override
    public void addCustomer(CustomerDTO dto) {
        //校验参数
        if(ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getName())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        //将DTO 转成实体 bean拷贝
        Customer customer = BeanUtil.copyProperties(dto, Customer.class);
        //补全创建时间
        customer.setCreateTime(LocalDateTime.now());
        //补全更新时间
        customer.setUpdateTime(LocalDateTime.now());

        this.save(customer);
    }

    /**
     * 客户列表查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<CustomerDO> customerList(CustomerListDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        List<CustomerDO> list = this.baseMapper.selectByPage(dto);
        Page<CustomerDO> page = (Page<CustomerDO>) list;
        PageResult<CustomerDO> result = PageResult.<CustomerDO>builder()
                .total(Long.valueOf( page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
        return result;
    }
}
